package com.caocaog.market.merchant.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.caocaog.market.constant.MarketConstant;
import com.caocaog.market.merchant.entity.MkMerchantBasic;
import com.caocaog.market.merchant.mapper.MkMerchantMapper;
import com.caocaog.market.merchant.service.MkMerchantService;
import com.caocaog.market.merchant.vo.MerchantCreateVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author liguang
 * @version 1.0.0
 * @Project jeecg-boot
 * @Package com.caocaog.market.merchant.service.impl
 * @ClassName MkMerchantServiceImpl.java
 * @createTime 2021年11月24日 18:40:00
 * @Description TODO
 */
@Slf4j
@Service
public class MkMerchantServiceImpl extends ServiceImpl<MkMerchantMapper, MkMerchantBasic> implements MkMerchantService {
    // 商家实名后的基础角色
    @Value("${merchant.role.named.basic}")
    private String merchantNamedBasic;
    // 商家实名后 如果类型为外卖类型的话，授予外卖角色
    @Value("${merchant.role.named.takeout}")
    private String merchantNamedTakeout;
    // 商家实名后 如果类型为服务类型的话，授予服务角色
    @Value("${merchant.role.named.serve}")
    private String merchantNamedServe;

    @Autowired
    private CommonAPI commonAPI;
    @Override
    public int insertOrUpdMkMerchant(MkMerchantBasic mkMerchantBasic) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(StringUtils.isNotBlank(mkMerchantBasic.getId())){
            // 修改
            UpdateWrapper<MkMerchantBasic> uw = new UpdateWrapper<MkMerchantBasic>();
            uw.eq("id",mkMerchantBasic.getId());
            uw.set("name",mkMerchantBasic.getName());
            uw.set("aliname",mkMerchantBasic.getAliname());
            uw.set("alipay",mkMerchantBasic.getAlipay());
            uw.set("idcard",mkMerchantBasic.getIdcard());
            uw.set("mobile",mkMerchantBasic.getMobile());
            uw.set("type",mkMerchantBasic.getType());
            uw.set("site_id",mkMerchantBasic.getSiteId());
            uw.set("state",mkMerchantBasic.getState());
            uw.set("front_idcard_url",mkMerchantBasic.getFrontIdcardUrl());
            uw.set("back_idcard_url",mkMerchantBasic.getBackIdcardUrl());
            uw.set("hand_held_idcard_url",mkMerchantBasic.getHandHeldIdcardUrl());
            return super.getBaseMapper().update(mkMerchantBasic,uw);
        }
        // 新增
        mkMerchantBasic.setId(IdWorker.getIdStr(mkMerchantBasic));
        mkMerchantBasic.setUserId(loginUser.getId());
        mkMerchantBasic.setCreateBy(loginUser.getUsername());
        mkMerchantBasic.setCreateTime(new Date());
        mkMerchantBasic.setState(0);
        return super.getBaseMapper().insertMkMerchant(mkMerchantBasic);
    }
    @Override
    public  List<MkMerchantBasic> validIdcard(String idcard,String merchantId){
        QueryWrapper<MkMerchantBasic> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("idcard",idcard);
        if(StringUtils.isNotBlank(merchantId)){
            queryWrapper.ne("id",merchantId);
        }
        List<MkMerchantBasic> basics= super.getBaseMapper().selectList(queryWrapper);
        return basics;
    }

    @Override
    public int updateRealnameByUserId(String userId, String realName) {
        return super.getBaseMapper().updateRealnameByUserId(userId,realName);
    }

    /**
     * 根据商家id获取商家信息
     * @param merchantId
     * @return
     */
    @Override
    public MkMerchantBasic findMerchantById(String merchantId) {

        return super.getBaseMapper().selectById(merchantId);
    }

    /**
     * 根据手机号查询该手机号是否被占用
     * @param mobile
     * @return
     */
    @Override
    public int findCountByMobile(String mobile,String merchantId) {
        QueryWrapper<MkMerchantBasic> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile",mobile);
        if(StringUtils.isNotBlank(merchantId)){
            queryWrapper.ne("id",merchantId);
        }
        int num = super.getBaseMapper().selectCount(queryWrapper);
        return num;
    }

    public List<MkMerchantBasic> findMerchantBySiteId(String siteId) {
        return baseMapper.selectList(new LambdaQueryWrapper<MkMerchantBasic>()
                .eq(org.apache.commons.lang3.StringUtils.isNotBlank(siteId), MkMerchantBasic::getSiteId, siteId));
    }

    @Override
    public MkMerchantBasic findByUserId(String userId) {
        return super.getBaseMapper().selectOne(new QueryWrapper<MkMerchantBasic>().eq("user_id",userId));
    }

    @Override
    public IPage<MkMerchantBasic> findMerchantList(Page<MkMerchantBasic> page, MkMerchantBasic mkMerchantBasic) {
        // 查询当前登录用户
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(null!=loginUser.getUserType() && loginUser.getUserType().equals(MarketConstant.USER_TYPE_SITE)){
            // 当前登录用户是分站用户
            mkMerchantBasic.setSiteId(loginUser.getSiteId());
        }
        return super.getBaseMapper().findMerchantList(page,mkMerchantBasic);
    }

    @Override
    public List<MkMerchantBasic> findMerchantListNoPage(MkMerchantBasic mkMerchantBasic) {
        return super.getBaseMapper().findMerchantList(mkMerchantBasic);
    }

    @Override
    public int checkMerchant(MkMerchantBasic basic) {
        UpdateWrapper<MkMerchantBasic> uw = new UpdateWrapper<MkMerchantBasic>();
        String type = basic.getType();
        uw.eq("id",basic.getId());
        uw.set("state",basic.getState());
        uw.set("grade",basic.getGrade());
        uw.set("type",type);
        uw.set("check_fail_reason",basic.getCheckFailReason());
        int count = super.getBaseMapper().update(basic,uw);
        // 审核通过才会授予实名后的角色
        if(count>0 && basic.getState().equals(MarketConstant.MERCHANT_CHECK_SHTG)){
            /** 判断类型 */
            String roleCodes = merchantNamedBasic;
            if(type.contains(MarketConstant.MARCHANT_CHECK_TAKEOUT)){
                roleCodes = roleCodes+","+merchantNamedTakeout;
            }
            if(type.contains(MarketConstant.MARCHANT_CHECK_SERVE)){
                roleCodes = roleCodes+","+merchantNamedServe;
            }
            // 审核操作执行成功，此时需要授予权限；只有在审核通过之后才会授予权限
            QueryWrapper<MkMerchantBasic> queryWrapper = new QueryWrapper<>();
            MkMerchantBasic merchant = super.getBaseMapper().selectById(basic.getId());
            String merchantUserId = merchant.getUserId();
            commonAPI.addOneOrManyRolesForUser(merchantUserId,roleCodes);
        }
        return count;
    }

    /**
     * 创建一个商家信息
     *
     * @param merchantCreateVO 创建一个商家信息用到的信息
     * @return 创建结构
     */
    @Override
    public MkMerchantBasic createMerchant(MerchantCreateVO merchantCreateVO) {
        MkMerchantBasic merchantBasic = new MkMerchantBasic();
        BeanUtil.copyProperties(merchantCreateVO,merchantBasic);
        // 默认使用管城区分站，系统只有一个分站。但是多店铺
        merchantBasic.setSiteId(CommonConstant.DEFAULT_SITE_ID);
        // 创建商家实体信息
        save(merchantBasic);
        return merchantBasic;
    }

}
